package com.appna.HelloLocation;

import java.util.Iterator;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class HelloLocation extends MapActivity {
	int tiempo = 60;//Segundos entre actualizaciones de posicion
	int distancia = 50;//Metros entre actualizaciones de posicion
	
	LocationManager locationManager;
	LocationListener locationListener;
	GpsStatus.Listener gpsListener;
	
	private MapController mapController;
	private MapView mapView;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ////////////////////////////////////////////////////////////////
        //Mapa
        mapView = (MapView) findViewById(R.id.mapView);
        mapController = mapView.getController();
        
        ////////////////////////////////////////////////////////////////
        //TABS
        TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
        tabHost.setup();
        TabSpec spec1=tabHost.newTabSpec(getString(R.string.Status));
        spec1.setContent(R.id.tab1);
        spec1.setIndicator(getString(R.string.Status),getResources().getDrawable(R.drawable.laptop));

        TabSpec spec2=tabHost.newTabSpec(getString(R.string.Sats));
        spec2.setIndicator(getString(R.string.Sats),getResources().getDrawable(R.drawable.chart));
        spec2.setContent(R.id.tab2);

        TabSpec spec3=tabHost.newTabSpec(getString(R.string.Map));
        spec3.setIndicator(getString(R.string.Map),getResources().getDrawable(R.drawable.globe));
        spec3.setContent(R.id.tab3);

        tabHost.addTab(spec1);
        tabHost.addTab(spec2);
        tabHost.addTab(spec3);

        ////////////////////////////////////////////////////////////////
        //GPS
        // Acquire a reference to the system Location Manager
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // Define a listener that responds to location updates
        locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
              // Called when a new location is found by the network location provider.
              actualizarTxtPos(location);
              actualizarMapa(location);
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {}

            public void onProviderEnabled(String provider) {}

            public void onProviderDisabled(String provider) {}
         };
          
		gpsListener = new GpsStatus.Listener() {
	         public void onGpsStatusChanged(int event) {
	        	 switch (event){
	        	 case GpsStatus.GPS_EVENT_FIRST_FIX:
	        		msgBox(getString(R.string.GpsFixed));
	        	 	mapController.setZoom(10);//queda bien?????????????????????????????????
	              break;
	              
	              case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
	            	  GpsStatus estadoGps = locationManager.getGpsStatus(null);

		              Iterator<GpsSatellite> satellites = estadoGps.getSatellites().iterator();
		              int i=0;
		              while (satellites.hasNext()) {
		            	  //Etiquetas de satelites
		            	  GpsSatellite sat = satellites.next();
		            	  TextView txtPrni = (TextView) findViewById(R.id.txtPrn1+i);
		            	  txtPrni.setText(sat.getPrn());
		            	  i++;
		            	  //Barras de cobertura
		            	  LinearLayout snri = (LinearLayout) findViewById(R.id.snr1+i);
		            	  ViewGroup.LayoutParams params = snri.getLayoutParams();
		            	  params.height=(int)sat.getSnr()*3;
		            	  snri.setLayoutParams(params);
		            	  //Constelacion de satelites
		            	  
		              }
		          break;
	        	 }
	          }
          };
          locationManager.addGpsStatusListener(gpsListener);
          
        localizar();
        //////////////////////////////////////////////////////////////
        //Acrtualizo el estado de la aplicacion
        actualizarEstado(this.getString(R.string.AquiringLocation) );
        actualizarTiempo(tiempo);
        actualizarDistancia(distancia);
        
        //////////////////////////////////////////////////////////////
        //Botones
        Button btnMasDist = (Button)findViewById(R.id.btnMasDist);
        btnMasDist.setOnClickListener(mBotonListener);
        Button btnMenosDist = (Button)findViewById(R.id.btnMenosDist);
        btnMenosDist.setOnClickListener(mBotonListener);
        Button btnMasTiempo = (Button)findViewById(R.id.btnMasTiempo);
        btnMasTiempo.setOnClickListener(mBotonListener);
        Button btnMenosTiempo = (Button)findViewById(R.id.btnMenosTiempo);
        btnMenosTiempo.setOnClickListener(mBotonListener);

        try {
        	   PackageManager manager = this.getPackageManager();
        	   PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
        	   TextView txtVersion = (TextView) findViewById(R.id.txtVersion);
        	   txtVersion.setText("Version: " + info.versionName + " ("+info.versionCode+")");
        	  } catch (Exception e) {
        	   System.out.println(" Exception in onCreate() : e = " + e);
        	  }
        	 
    }
    /////////////////////////////////////////////////////////////////
    //Menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.app_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.mnuQuit:
            quit();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    @Override
    protected void onPause(){
    	super.onPause();
    	locationManager.removeUpdates(locationListener);
    	//msgBox(getString(R.string.GpsDisable));
    }
    @Override
    protected void onResume(){
    	super.onResume();
    	localizar();
    }
    
    private OnClickListener mBotonListener = new OnClickListener(){
    	public void onClick(View v) {	
	    	switch (v.getId()) {
	    	case R.id.btnMasDist:
	    		distancia=distancia+10;
	            localizar();
	            actualizarDistancia(distancia);
	    		break;
	    	case R.id.btnMenosDist:
	    		if(distancia>10){distancia=distancia-10;}
	            localizar();
	            actualizarDistancia(distancia);
	    		break;
	    	case R.id.btnMasTiempo:
	    		tiempo=tiempo+10;
	            localizar();
	            actualizarTiempo(tiempo);
	    		break;
	    	case R.id.btnMenosTiempo:
	    		if(tiempo>10){tiempo=tiempo-10;}
	            localizar();
	            actualizarTiempo(tiempo);
	    		break;
	    	}
    	}
	};
	
	private void quit() {
		locationManager.removeUpdates(locationListener);
		try {
			super.finish();
		} catch (Throwable e) {
			msgBox("Error");
			e.printStackTrace();
		}
	}
	
    public void msgBox(String message){
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
    }
    private void actualizarTxtPos (Location location) {
    	TextView txtLatitud = (TextView) findViewById(R.id.txtLatitud);
    	TextView txtLongitud = (TextView) findViewById(R.id.txtLongitud);
    	TextView txtAltitud = (TextView) findViewById(R.id.txtAltitud);
    	TextView txtPrecision = (TextView) findViewById(R.id.txtPrecision);
    	
    	String latitud=String.valueOf(location.getLatitude());
    	String longitud=String.valueOf(location.getLongitude());
    	String altitud=String.valueOf(location.getAltitude());
    	String precision=String.valueOf(location.getAccuracy());
    	
    	txtLatitud.setText( this.getString(R.string.Lat) + ": " + latitud );
    	txtLongitud.setText( this.getString(R.string.Lon) + ": " + longitud );
    	txtAltitud.setText( this.getString( R.string.Alt) + ": " + altitud );
    	txtPrecision.setText( this.getString(R.string.Pre) + ": " + precision );
    }
    private void actualizarEstado(String estado) {
    	TextView txtEstado = (TextView) findViewById(R.id.txtEstado);
    	txtEstado.setText(estado);
    }
    private void actualizarTiempo(int t) {
    	TextView txttiempo = (TextView) findViewById(R.id.txtTiempoActualizacion);
    	txttiempo.setText(this.getString(R.string.TiempoAct) + ": " + String.valueOf(t));
    }
    private void actualizarDistancia(int d) {
    	TextView txtdistancia = (TextView) findViewById(R.id.txtDistActualizacion);
    	txtdistancia.setText(this.getString(R.string.DistanciaAct) +": "+ String.valueOf(d));
    }
    
    //////////////////////////////////////////////////////////////
    //Esto tiene muy mala pinta.... 
    private void localizar() {

          //Primero obtenemos la ultima localizaci'on conocida y luego empezamos a buscar
          //Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
          //actualizamos la posici'on
         // ActualizarTxt(lastKnownLocation);
        // Register the listener with the Location Manager to receive location updates
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, tiempo, distancia, locationListener);
    }
    //private void enviarByte(byte dato) {
    //	
    //}
    @Override
    protected boolean isRouteDisplayed() {
    return false;
    }
    private void actualizarMapa(Location location) {
    	GeoPoint point = new GeoPoint((int)(location.getLatitude()*1E6), (int)(location.getLongitude()*1E6));
    	mapController.setCenter(point);
    }
}